import sys
import datetime
import subprocess
import time
import os
import re
from datetime import datetime, timedelta

def hilog_capture(capture_duration):
    # 获取当前日期时间
    current_time = datetime.now().strftime("%Y%m%d%H%M%S")
    # 生成文件名
    log_file_name = f"hilog_{current_time}.log"
    # 执行hdc hilog命令并写入log_file_name文件
    with open(log_file_name, 'w') as f:
        # 启动hdc hilog命令
        process = subprocess.Popen(["hdc", "hilog"], stdout=f, stderr=f)
        # 等待capture_duration时间
        time.sleep(int(capture_duration) * 60)  # 将分钟转换为秒
        # 发送信号给hdc hilog命令，以停止执行
        process.terminate()
    return log_file_name

def hilog_analysis(log_file_name,search_string ):
    # 初始化结果列表
    results = []
    # 打开并读取日志文件
    try:
        with open(log_file_name, 'r',encoding="UTF-8",errors='ignore') as file:
            # 逐行读取文件
            for line in file:
                # 如果行中包含搜索字符串
                if search_string in line:
                    # 将该行添加到结果列表
                    results.append(line)
    except FileNotFoundError:
        print(f"Error: The file {log_file_name} was not found.")
        return
    except Exception as e:
        print(f"Error: An unexpected error occurred: {e}")
        return

    # 写入结果到result.txt
    with open('result.txt', 'w') as result_file:
        if results:
            # 如果找到匹配的行，写入这些行
            result_file.writelines(results)
            print("\033[1;32m蓝牙标签已检索到！\033[0m")
        else:
            # 如果没有找到匹配的行，写入提示信息
            result_file.write("蓝牙标签数据未检索到")
            print("\033[1;31m蓝牙标签未检索到！\033[0m")


def hilog_id_parse(result_file,check_duration):
    # 正则表达式模式
    timestamp_pattern = r'^\S+\s+(\S+)'
    device_id_pattern = r'id_rsa_data:(\S+),'

    # 检查时长的时间范围
    check_duration_range = timedelta(minutes=check_duration)
    # 指定的设备ID范围
    device_ids = {"SP55555555", "BM55555555", "CM55555555", "EV55555555"}
    
    try:
        # 打开文件并读取所有行
        with open(result_file, 'r') as file:
            lines = file.readlines()
        # 打开id_check.txt文件，用于写入解析结果
        with open("id_check.txt", 'w') as check_file:
            # 解析每一行
            for line in lines:
                # 提取上报时间
                timestamp_match = re.search(timestamp_pattern, line)
                timestamp = timestamp_match.group(1) if timestamp_match else None

                # 提取设备ID
                device_id_match = re.search(device_id_pattern, line)
                device_id = device_id_match.group(1) if device_id_match else None

                # 打印结果
                if timestamp and device_id:
                     # 检查设备ID是否在指定范围内
                    if device_id in device_ids:
                        # 计算上报时间与基准时间的差值
                        base_time = datetime.now()
                        base_time_str = base_time.strftime("%H:%M:%S.%f")
                        time_difference = datetime.strptime(timestamp, "%H:%M:%S.%f") - datetime.strptime(base_time_str, "%H:%M:%S.%f")
                        if abs(time_difference) <= check_duration_range:
                             print(f"上报时间: {timestamp} 设备ID: {device_id} 在检查范围内")
                             # 写入id_check.txt文件
                             check_file.write(f"上报时间: {timestamp} 设备ID: {device_id}\n")                       	
    except FileNotFoundError:
        print(f"Error: The file {result_file} was not found.")
    except Exception as e:
        print(f"Error: An unexpected error occurred: {e}")

def hilog_id_check(file_name):
    
    # 指定的设备ID范围
    device_ids = {"SP55555555", "BM55555555", "CM55555555", "EV55555555"}

    # 检查文件大小是否为0字节
    if os.path.getsize(file_name) == 0:
        print(f"\033[1;31m蓝牙标签文件{file_name}为空文件\033[0m")
        return "Error: The file is empty."
        
    # 尝试打开文件
    try:
        with open(file_name, 'r', encoding="UTF-8", errors='ignore') as file:
            # 读取整个文件内容
            content = file.read()
            # 检查文件内容是否包含device_id
            for device_id in device_ids:
                if device_id not in content:
                     # 如果没有找到任何匹配的device_id，返回提示信息
                     print(f"\033[1;31m蓝牙标签{device_id}未检索到\033[0m")
    except FileNotFoundError:
        return f"Error: The file {file_name} was not found."
    except Exception as e:
        return f"Error: An unexpected error occurred: {e}"

def main(command_type, parameter,parameter_2):
    if command_type == "capture":
        capture_duration = parameter
        log_file_name = hilog_capture(capture_duration)
        print(log_file_name)  # 打印文件名，Jenkins会捕获这个输出        
    elif command_type == "analysis":
        log_file_name = parameter
        hilog_analysis(log_file_name,"id_rsa_data")
    elif command_type == "parse":
        result_file = parameter
        check_duration = parameter_2
        hilog_id_parse(result_file,check_duration)
        #hilog_id_check("id_check.txt")
    else:
        print("Unknown command type")
        return

if __name__ == "__main__":
    if len(sys.argv) == 4:
        command_type = sys.argv[1]
        parameter = sys.argv[2]
        parameter_2 = int(sys.argv[3])        
        main(command_type, parameter,parameter_2)
    else:
        print("Usage: Bluetooth_tags.py <command_type> <parameter> <parameter_2>")
